#include "ccalendarevent.h"

namespace buola { namespace bcal {

CCalendarEvent::CCalendarEvent(const CCalendarTime &pStart,const CCalendarTime &pEnd)
    :   mCalendar(nullptr),
        mStart(pStart),
        mEnd(pEnd),
        mIsAllDay(false)
{
    mComponent=icalcomponent_new_vevent();

    icalcomponent_set_dtstart(mComponent,icaltime_from_string(
                        utf8(CDateTime(pStart).GetISODateTime()).c_str()));
    icalcomponent_set_dtend(mComponent,icaltime_from_string(
                        utf8(CDateTime(pEnd).GetISODateTime()).c_str()));
}

CCalendarEvent::CCalendarEvent(CCalendar *pCalendar,icalcomponent *pC)
    :   mCalendar(pCalendar),
        mComponent(pC)
{
    icaltimetype lIStart=icaltime_convert_to_zone(
                            icalcomponent_get_dtstart(mComponent),
                            icaltimezone_get_utc_timezone());
    icaltimetype lIEnd=icaltime_convert_to_zone(
                            icalcomponent_get_dtend(mComponent),
                            icaltimezone_get_utc_timezone());

    if(icaltime_is_date(lIStart))
    {
        mStart=CDate(lIStart.year,lIStart.month,lIStart.day).GetStartTime();
    }
    else
    {
        mStart=CCalendarClock::from_time_t(icaltime_as_timet(lIStart));
    }
    if(icaltime_is_date(lIEnd))
    {
        mEnd=CDate(lIEnd.year,lIEnd.month,lIEnd.day).GetStartTime();
    }
    else
    {
        mEnd=CCalendarClock::from_time_t(icaltime_as_timet(lIEnd));
    }

    mIsAllDay=icaltime_is_date(lIStart)&&icaltime_is_date(lIEnd);
}

CCalendarEvent::~CCalendarEvent()
{
}

bool CCalendarEvent::IsBetween(const CCalendarTime &pFrom,const CCalendarTime &pTo)
{
    return (mEnd>pFrom&&mStart<pTo);
}

std::wstring CCalendarEvent::GetSummary()
{
    const char *lSummary=icalcomponent_get_summary(mComponent);

    if(lSummary)
        return utf32(lSummary);
    else
        return std::wstring();
}

std::wstring CCalendarEvent::GetDescription()
{
    const char *lDesc=icalcomponent_get_description(mComponent);

    if(lDesc)
        return utf32(lDesc);
    else
        return std::wstring();
}

void CCalendarEvent::SetStart(const CCalendarTime &pStart)
{
    mStart=pStart;
    icalcomponent_set_dtstart(mComponent,icaltime_from_string(utf8(CDateTime(pStart).GetISODateTime()).c_str()));
}

void CCalendarEvent::SetEnd(const CCalendarTime &pEnd)
{
    mEnd=pEnd;
    icalcomponent_set_dtend(mComponent,icaltime_from_string(utf8(CDateTime(pEnd).GetISODateTime()).c_str()));
}

void CCalendarEvent::SetSummary(const std::wstring &pSummary)
{
    icalcomponent_set_summary(mComponent,utf8(pSummary).c_str());
}

void CCalendarEvent::SetDescription(const std::wstring &pDesc)
{
    icalcomponent_set_description(mComponent,utf8(pDesc).c_str());
}

void CCalendarEvent::Dump(io::CTextWriter &pWriter)
{
    pWriter << icalcomponent_as_ical_string(mComponent) << "\n";
}

/*namespace buola*/ } /*namespace bcal*/ }
